package com.clotingshoppos.modules.order.service.serviceImpl;

import com.clotingshoppos.common.util.TimeSplit;
import com.clotingshoppos.modules.Shiro.repository.UserRepository;
import com.clotingshoppos.modules.order.POJO.*;
import com.clotingshoppos.modules.order.entity.OrderDetailEntity;
import com.clotingshoppos.modules.order.entity.OrderEntity;
import com.clotingshoppos.modules.order.repository.OrderDetailRepository;
import com.clotingshoppos.modules.order.repository.OrderRepository;
import com.clotingshoppos.modules.order.service.OrderService;
import com.clotingshoppos.modules.order.service.Statistic;
import com.clotingshoppos.modules.product.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @ClassName: OrderServiceImpl
 * @Description:
 * @Author: Izzat
 * @Date: 2019-04-21 20:02
 * @Version: v1.0
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ProductRepository productRepository;

    @Override
    public Page<OrderEntity> findAll(Pageable pageable) {
        return orderRepository.findAll(pageable);
    }

    @Override
    public OrderEntity save(OrderRelate orderRelate) {
        OrderEntity order = orderRepository.save(orderRelate.getOrderInfo());
        for(OrderDetailEntity e : orderRelate.getItemList()){
            e.setOrderId(order.getId());
            orderDetailRepository.save(e);
        }
        return order;
    }

    @Override
    public OrderRelate findFullOrder(OrderEntity orderEntity) {
        //根据订单id查找订单信息
        OrderEntity orderInfo = (OrderEntity)findById(orderEntity.getId());
        //把收银员由id转换为姓名
        orderInfo.setStuff(userRepository.findById(orderInfo.getStuff()).map(s -> s.getUsername()).orElse(null));
        //根据订单id查找订单子表的记录
        List<OrderDetailEntity> items = orderDetailRepository.findByOrderId(orderEntity.getId()).orElse(null);
        //把货品id转换为name
        for(OrderDetailEntity e : items){
            e.setProduct(productRepository.findById(e.getProduct()).orElse(null).getName());
        }
        //组装返回的订单
        OrderRelate orderRelate = new OrderRelate(orderInfo, items);
        return orderRelate;
    }

    @Override
    public Double getTotalPrice(List<OrderDetailEntity> list) {
        //总价
        Double totalPrice  = 0.0;
        //某件商品单价
        Double singlePrice = 0.0;
        for (OrderDetailEntity e : list){
            singlePrice = Double.parseDouble(productRepository.findById(e.getProduct()).map(product -> product.getPrice()).orElse("0.0"));
            totalPrice += e.getNumber() * singlePrice;
        }
        return totalPrice;
    }

    @Override
    public OrderEntity pay(PayStatus payStatus) {
        //根据订单id找到订单
        OrderEntity order = (OrderEntity)findById(payStatus.getOrderId());
        //判断支付是否成功
        if(payStatus.isStatus()){//成功则修改对应订单的对应字段
            order.setStatus("1");
            order.setProceeds(payStatus.getProceeds());
            order.setChange(payStatus.getChange());
            order.setReceivable(payStatus.getReceivable());
            order.setMethod(payStatus.getMethod());
            return update(order);
        }else //支付失败，直接返回null
            return null;

    }

    @Override
    public List<OrderEntity> findByDate() {
        return null;
    }

    @Override
    public StatisticsData statistics(StatisticsData date) {
        return null;
    }

    @Override
    public EChartResForProduct CountingClothes() {
        Statistic statistic =  () -> {
            //查找已经成功交易的不同产品的销量统计
            List<OrderDetailEntity> list = orderDetailRepository.countByProduct();
            //把数据组装为返回的格式
            return addToEchartData(list,1);
        };
        return (EChartResForProduct)statistic.Statistic();
    }

    @Override
    public EChartResForProduct CountingClothesByStuff(String timeSpan) {
        return null;
    }

    @Override
    public EChartResForStuff CountingClothesByStuff(String sutff, String timeSpan) {
        //获取时间范围(timeSpan)指定的时间戳格式的起止时间
        Timestamp[] time  = TimeSplit.execute(timeSpan);
        Statistic statistic =  () -> {
            //查找已经成功交易的指定营业员的不同产品的销量统计
            List<OrderDetailEntity> list = orderDetailRepository.countByProductByStuff(sutff, time[0], time[1]);
            //把数据组装为返回的格式
            return addToEchartData(list, 2);
        };
        return (EChartResForStuff) statistic.Statistic();
    }

    @Override
    public EChartResForProduct CountingClothesWithTime(String timeSpan) {
        //获取时间范围(timeSpan)指定的时间戳格式的起止时间
        Timestamp[] time  = TimeSplit.execute(timeSpan);
        Statistic statistic = () -> {
            //查找已经成功交易的指定时间内的的不同产品的销量统计
            List<OrderDetailEntity> list = orderDetailRepository.countByProductWithTime(time[0], time[1]);
            //把数据组装为返回的格式
            return addToEchartData(list,1);
        };
        return (EChartResForProduct)statistic.Statistic();
    }

    /**
    * @Description: 把查询结果组装为返回的格式
    * @Param: list 查询得到的数据
    * @Param: type 需要返回的类型 1->产品相关 2->雇员相关
    * @return:
    * @Author: Izzat
    * @Date: 2019/5/19  12:28
    */
    public EChartRes addToEchartData(List<OrderDetailEntity> list, int type){
        //定义两个分别存储产品名和销量的数组
        List<String> name = new ArrayList<>();
        List<Integer> number = new ArrayList<>();
        //遍历查找的结果，存储到定义的数组里
        for(OrderDetailEntity e : list){
            name.add(e.getProduct());
            number.add(e.getNumber());
        }
        EChartRes res = null;
        if(type == 1){
            res = new EChartResForProduct(name, number);
        }else {
            Double Sale = 0.0;
            for(OrderDetailEntity e : list){
                Sale += e.getTotalPrice();
            }
             res = new EChartResForStuff(name, number, Sale);
        }
        return res;
    }

    @Override
    public OrderEntity add(OrderEntity orderEntity) {
        return orderRepository.save(orderEntity);
    }

    @Override
    public OrderEntity findById(String t) {
        Optional<OrderEntity> order = orderRepository.findById(t);
        return order.orElse(null);
    }

    @Override
    /**
    * @Description: 更新订单状态
    * @Param: [orderEntity]
    * @return: com.clotingshoppos.modules.order.entity.OrderEntity
    * @Author: Izzat
    * @Date: 2019/4/21  20:08
    */
    public OrderEntity update(OrderEntity orderEntity) {
        if(findById(orderEntity.getId()) != null){
            return orderRepository.save(orderEntity);
        }else
            return null;
    }

    @Override
    //订单生成不可删除
    public OrderEntity delete(OrderEntity orderEntity) {
        return null;
    }
}
